package com.kasax.plugin.shadow.visitor

import com.kasax.plugin.shadow.utils.LogUtils
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes

class LifecycleClassVisitor extends ClassVisitor implements Opcodes {
    private String className
    private static final Set<String> LIFECYCLE_METHODS = [
            "onCreate",
            "onStart",
            "onResume",
            "onPause",
            "onStop",
            "onDestroy"
    ]

    LifecycleClassVisitor(ClassVisitor cv) {
        super(Opcodes.ASM7, cv)
    }

    @Override
    void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        this.className = name
        super.visit(version, access, name, signature, superName, interfaces)
    }

    @Override
    MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor mv = cv.visitMethod(access, name, descriptor, signature, exceptions)
        if (name in LIFECYCLE_METHODS) {
            LogUtils.d("LifecycleClassVisitor", "Injecting lifecycle log for $className.$name")
            return new LifecycleMethodVisitor(mv, name)
        }
        return mv
    }
}
